package com.hanthink.web.controller.app.repair;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import com.github.pagehelper.util.StringUtil;
import com.hanthink.common.annotation.Anonymous;
import com.hanthink.common.enums.PushType;
import com.hanthink.system.domain.EmXflh;
import com.hanthink.system.domain.repair.*;
import com.hanthink.system.mapper.EmXflhMapper;
import com.hanthink.system.mapper.repair.*;
import com.hanthink.system.service.impl.WeChatMessageServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.constant.HttpStatus;
import com.hanthink.common.core.controller.BaseController;
import com.hanthink.common.core.domain.AjaxResult;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.core.page.TableDataInfo;
import com.hanthink.common.utils.ServletUtils;
import com.hanthink.framework.web.service.TokenService;
import com.hanthink.system.domain.pc.EmEquip;
import com.hanthink.system.domain.pc.EmFaultCode;
import com.hanthink.system.domain.pc.EmFaultType;
import com.hanthink.system.domain.pc.EmFaultTypeAndCode;
import com.hanthink.system.mapper.EmEquipMapper;
import com.hanthink.system.mapper.EmFaultCodeMapper;
import com.hanthink.system.mapper.EmFaultTypeMapper;
import com.hanthink.system.service.repair.IRepairRecordInfoService;
import com.hanthink.system.service.repair.IRepairRecordTimeService;

@RestController
@RequestMapping("/app/repair/repairInfo")
public class RepairInfoControll extends BaseController {

    @Autowired
    private IRepairRecordInfoService repairRecordInfoService;

    @Autowired
    private IRepairRecordTimeService repairRecordTimeService;

    @Autowired
    private RepairRecoedMapper repairRecoedMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private EquipRepairMapper equipRepairMapper;

    @Autowired
    private EmEquipMapper emEquipMapper;

    @Autowired
    private EmFaultTypeMapper emFaultTypeMapper;

    @Autowired
    private EmFaultCodeMapper emFaultCodeMapper;

    @Autowired
    private RequestMapper requestMapper;

    @Autowired
    private EmXflhMapper emxflhMapper;
    @Autowired
    private WeChatMessageServiceImpl weChatMessageService;

    @Autowired
    private RepairPlanMapper repairPlanMapper;
    @Autowired
    private RepairTaskMapper repairTaskMapper;

    @PostMapping("/wiatExecutelist")
    public TableDataInfo list(@RequestBody Map<String, Object> map) {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        for (int e = 0; e < loginUser.getUser().getRoles().size(); e++) {
            if (loginUser.getUser().getRoles().get(e).getRoleName().contains("隐患")) {
                String[] temp = loginUser.getUser().getRoles().get(e).getRoleName().split("-");
                map.put("deptname", temp[1]);
                break;
            }
        }
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitRepairList(map);
        return getDataTable(list);
    }


    @PostMapping("/wiatExecutelistbyCode")
    public TableDataInfo listbyCode(@RequestBody Map<String, Object> map) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        dataMap.put("id", map.get("id").toString());
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitRepairListbyCode(dataMap);
        return getDataTable(list);
    }

    @PostMapping("/wiatExecutelistsj")
    public TableDataInfo listsj(@RequestBody Map<String, Object> map) {
        startPage();
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitRepairListsj(map);
        return getDataTable(list);
    }

    @PostMapping("/wiatChecklist")
    public TableDataInfo selectWaitCheckList(@RequestBody Map<String, Object> map) {
        startPage();
        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.put("userName", loginUser.getUser().getUserName());
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitCheckList(map);
        return getDataTable(list);
    }

    @PostMapping("/wiatChecklistRole")
    public TableDataInfo selectWaitCheckListRole(@RequestBody Map<String, Object> map) {
        startPage();
        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.put("userName", loginUser.getUser().getUserName());
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitCheckListRole(map.get("site").toString(), map.get("deptname").toString(), map.get("userName").toString());
        return getDataTable(list);
    }


    @PostMapping("/wiatChecklistRoleqx")
    public TableDataInfo selectWaitCheckListRoleqx(@RequestBody Map<String, Object> map) {
        startPage();
        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.put("userName", loginUser.getUser().getUserName());
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitCheckListRoleqx(map.get("site").toString(), map.get("deptname").toString(), map.get("userName").toString());
        return getDataTable(list);
    }

    @PostMapping("/wiatChecklistRoleqx1")
    public TableDataInfo selectWaitCheckListRoleqx1(@RequestBody Map<String, Object> map) {
        startPage();
        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.put("userName", loginUser.getUser().getUserName());
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitCheckListRoleqx1(map.get("site").toString(), map.get("deptname").toString(), map.get("userName").toString());
        return getDataTable(list);
    }

    @PostMapping("/wiatChecklistRoleqx2")
    public TableDataInfo selectWaitCheckListRoleqx2(@RequestBody Map<String, Object> map) {
        startPage();
        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.put("userName", loginUser.getUser().getUserName());
        List<RepairRecordInfo> list = repairRecordInfoService.selectWaitCheckListRoleqx2(map.get("site").toString(), map.get("deptname").toString(), map.get("userName").toString());
        return getDataTable(list);
    }

    @PostMapping("/updateRepairStatus")
    public TableDataInfo updateRepairStatus(@RequestBody Map<String, Object> map) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.put("repairUser", loginUser.getUser().getUserName());
        map.put("siteKey", loginUser.getUser().getSite());
        repairRecordInfoService.updateRepairStatus(map);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }


    @PostMapping("/updateRepairStatusplus")
    public TableDataInfo updateRepairStatusplus(@RequestBody Map<String, Object> map) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        map.put("repairUser", loginUser.getUser().getUserName());
        map.put("siteKey", loginUser.getUser().getSite());
        repairRecordInfoService.updateRepairStatusplus(map);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }


    // 计算小时差
    private static long calculateHoursDifference(LocalDateTime dateTime1, LocalDateTime dateTime2) {
        return Math.abs(dateTime1.until(dateTime2, ChronoUnit.MINUTES));
    }

    @PostMapping("/finishRepaircommon")
    public TableDataInfo finishRepaircommon(@RequestBody Map<String, Object> map) {
        Object recordId = map.get("recordId"); // 维修记录ID
        Object sparePartCode = map.get("sparePartCode");// 备件更换记录
        Object faultType = map.get("faultType");// 故障类型
        Object finishTime = map.get("finishTime");// 完成时间
        Object repairUser = map.get("repairUser");// 维修人
        Object requestId = map.get("requestId");// 报修单ID
        Object siteKey = map.get("siteKey");// 工厂ID
        Object remark = map.get("remark");// 备注
        Object mergescale = map.get("mergescale");// 备注
        Object equipName = map.get("equipName");

        // 更新维修时间记录信息
        RepairRecordTime repairRecordTime = new RepairRecordTime();
        repairRecordTime.setRecordId(Long.valueOf(recordId.toString()));
        repairRecordTime.setStopReson("整改完成");
        repairRecordTimeService.updateRecordTime(repairRecordTime);

        RequestInfo requestInfo = requestMapper.selectRequestVoById(Long.valueOf(requestId.toString()));
        // 更新维修记录状态
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("status", BusinessConstants.REPAIR_STATUS_FINISH);
        params.put("id", repairRecordTime.getRecordId());
        params.put("faultType", faultType);
        params.put("remark", remark);
        params.put("sparePartCode", sparePartCode);
        params.put("mergescale", mergescale);
        repairRecoedMapper.updateRepairStatus(params);
        String pushMessage = "隐患编号:" + "【" + requestInfo.getRequestCode() + "】\n设备名称：" + equipName + "隐患已整改完成，请审核。";
        weChatMessageService.sendMessage(requestInfo.getSiteKey(), pushMessage, PushType.PUSH_TYPE_ONE.getValue(), null);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("维修完成");
        return rspData;
    }


    public static void sendWeChatMessageToUser(String msg, String user) {
        try {
            if (StringUtil.isEmpty(msg)) {
                return;
            }
            String yinhuanpaicha = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c3b95aaf-5808-4d15-867c-bcbe08d4123b";
            String TEXT = "text";
            // 封装发送消息请求JSON
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("{");
            stringBuffer.append("\"msgtype\":" + "\"" + TEXT + "\",");
            stringBuffer.append("\"text\":" + "{");
            stringBuffer.append("\"content\":" + "\"" + msg + "\"");
            stringBuffer.append(",\"mentioned_list\":" + "[\"" + user + "\"]");
            stringBuffer.append("}");
            stringBuffer.append("}");
            String json = stringBuffer.toString();

            URL postUrl = new URL(yinhuanpaicha);
            HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();
            // 写入内容
            OutputStream outputStream = http.getOutputStream();
            outputStream.write(json.getBytes(StandardCharsets.UTF_8));
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] jsonBytes = new byte[size];
            inputStream.read(jsonBytes);
            String result = new String(jsonBytes, StandardCharsets.UTF_8);
            System.out.println("请求返回结果:" + result);

            // 清空输出流
            outputStream.flush();
            // 关闭输出通道
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/add")
    public void add(@RequestBody Map<String, Object> map) {
        Object equipKey = map.get("equipKey");
        Object leftStation = map.get("leftStation");
        Object rightStation = map.get("rightStation");
        Object commonParts = map.get("commonParts");
        Object auxiliaryEquip = map.get("auxiliaryEquip");
        Object createTime = map.get("createTime");
        Object createdBy = map.get("createdBy");

        LocalDateTime now = LocalDateTime.now();
        String a = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toString();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("equipKey", equipKey.toString());
        params.put("leftStation", leftStation.toString());
        params.put("rightStation", rightStation.toString());
        params.put("commonParts", commonParts.toString());
        params.put("auxiliaryEquip", auxiliaryEquip.toString());
        params.put("createTime", a.toString());
        params.put("createdBy", createdBy.toString());
        emxflhMapper.insertInfo(params);
    }

    @PostMapping("/xflhlist")
    public TableDataInfo xflhlist(@RequestBody Map<String, Object> map) {
        Object equipKey = map.get("equipKey");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("equipKey", equipKey.toString());
        List<EmXflh> list = emxflhMapper.selectList(params);
        return getDataTable(list);
    }

    @PostMapping("/finishRepair")
    public TableDataInfo finishRepair(@RequestBody Map<String, Object> map) {
        Object recordId = map.get("recordId"); // 维修记录ID
        Object sparePart = map.get("sparePart");// 备件更换记录
        Object faultType = map.get("faultType");// 故障类型
        Object finishTime = map.get("finishTime");// 完成时间
        Object repairUser = map.get("repairUser");// 维修人
        Object requestId = map.get("requestId");// 报修单ID
        Object siteKey = map.get("siteKey");// 工厂ID
        Object remark = map.get("remark");// 备注
        Object mergescale = map.get("mergescale");// 备注

        if (sparePart != null && !"".equals(sparePart)) {
            // 记录备件更换信息
        }
        // 更新维修时间记录信息
        RepairRecordTime repairRecordTime = new RepairRecordTime();
        repairRecordTime.setRecordId(Long.valueOf(recordId.toString()));
        repairRecordTime.setStopReson("维修完成");
        repairRecordTimeService.updateRecordTime(repairRecordTime);
        // 更新维修记录状态
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("status", BusinessConstants.REPAIR_STATUS_FINISH);
        params.put("id", repairRecordTime.getRecordId());
        params.put("faultType", faultType);
        params.put("remark", remark);
        params.put("mergescale", mergescale);

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //System.out.println(dateFormat.format(date));

        //当前时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        RequestInfo rq = requestMapper.selectRequestVoById(repairRecordTime.getRecordId());

        RepairRecordInfo re = repairRecoedMapper.selectRecordByIdplus(repairRecordTime.getRecordId());
        // 将时间字符串转换为LocalDateTime对象
        LocalDateTime datenow = LocalDateTime.parse(dateFormat.format(date), formatter);
        //报修时间
        LocalDateTime dateTime1 = LocalDateTime.parse(rq.getRequestTime().substring(0, 19), formatter);
        //点击接单按钮时间
        LocalDateTime dateTime2 = LocalDateTime.parse(re.getCreatetime().substring(0, 19), formatter);
//		//开始维修时间
//		LocalDateTime dateTime3 = LocalDateTime.parse(re.getStartTime().substring(0,19), formatter);
//		//结束维修时间
//		LocalDateTime dateTime4 = LocalDateTime.parse(re.getEndTime().substring(0,19), formatter);
        //并修开始时间
        LocalDateTime dateTime5 = LocalDateTime.parse(re.getAuditdatetime().substring(0, 19), formatter);

        // 计算小时差
        long totalmaintenancetime = calculateHoursDifference(dateTime1, datenow);
        long orderreceivingtime = calculateHoursDifference(dateTime1, dateTime2);
        long waitingtime = calculateHoursDifference(dateTime5, dateTime1);
        long concurrentrepairtime = calculateHoursDifference(dateTime5, datenow);

        params.put("totalmaintenancetime", totalmaintenancetime);
        params.put("timeplus", orderreceivingtime);
        params.put("waitingtime", waitingtime);
        params.put("concurrentrepairtime", concurrentrepairtime);

        repairRecoedMapper.updateRepairStatussj(params);

        // 查询维修记录
        RepairRecordInfo repairRecordInfo = repairRecoedMapper.selectRecordByRecordId(recordId.toString());

        //int newRequestId = (int) repairRecordTime.getRecordId();
        // 查询报修记录
        RequestInfo requestInfo = requestMapper.selectRequestVoById(repairRecordTime.getRecordId());
        // 插入消息通知记录
        EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
        equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_TRUE);
        equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
        equipRepairMessageVo.setNewsType("维修验收");
        equipRepairMessageVo.setSendUser(requestInfo.getRequestUser());
        equipRepairMessageVo.setSiteKey(Long.valueOf(map.get("siteKey").toString()));

        Long relationId = Long.valueOf(repairRecordTime.getRecordId());
        equipRepairMessageVo.setRelationId(relationId);

        int newsiteKey = (int) siteKey;
        Long site = Long.valueOf(newsiteKey);
        equipRepairMessageVo.setSiteKey(site);
        equipRepairMessageVo.setEqKey(repairRecordInfo.getEqKey());
        equipRepairMessageVo.setNotingUser(repairRecordInfo.getRequestUser());
        // 根据设备id查询设备信息
//        EmEquip emEquip = emEquipMapper.selectEmEquipById(repairRecordInfo.getEqKey());
//        equipRepairMessageVo.setNewsDesc(
//                "【维修验收】\n" + emEquip.getDesc() + "[" + emEquip.getName() + "]\n单号：" + repairRecordInfo.getRepairCode()
//                        + "\n维修完成时间：" + finishTime.toString() + "\n维修人：" + repairUser.toString() + "\n请及时验收");
//        equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);
//
//        //在向群里发一条
//        equipRepairMessageVo.setNotingUser("@all");
//        equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("维修完成");
        return rspData;
    }

    /**
     * 维修完成
     *
     * @param map
     * @return
     */
    @PostMapping("/finishRepairplus")
    public TableDataInfo finishRepairplus(@RequestBody Map<String, Object> map) {
        Object recordId = map.get("recordId"); // 维修记录ID
        Object sparePart = map.get("sparePart");// 备件更换记录
        Object faultType = map.get("faultType");// 故障类型
        Object finishTime = map.get("finishTime");// 完成时间
        Object repairUser = map.get("repairUser");// 维修人
        Object requestId = map.get("requestId");// 报修单ID
        Object siteKey = map.get("siteKey");// 工厂ID
        Object remark = map.get("remark");// 备注

        if (sparePart != null && !"".equals(sparePart)) {
            // 记录备件更换信息
        }
        // 更新维修时间记录信息
        RepairRecordTime repairRecordTime = new RepairRecordTime();
        repairRecordTime.setRecordId(Long.valueOf(recordId.toString()));
        repairRecordTime.setStopReson("维修完成");
        repairRecordTimeService.updateRecordTime(repairRecordTime);
        // 更新维修记录状态
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("status", BusinessConstants.REPAIR_STATUS_FINISH);
        params.put("id", repairRecordTime.getRecordId());
        params.put("faultType", faultType);
        params.put("remark", remark);

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //System.out.println(dateFormat.format(date));

        //当前时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        RequestInfo rq = requestMapper.selectRequestVoById(repairRecordTime.getRecordId());

        RepairRecordInfo re = repairRecoedMapper.selectRecordByIdplus(repairRecordTime.getRecordId());
        // 将时间字符串转换为LocalDateTime对象
        LocalDateTime datenow = LocalDateTime.parse(dateFormat.format(date), formatter);
        //报修时间
        LocalDateTime dateTime1 = LocalDateTime.parse(rq.getRequestTime().substring(0, 19), formatter);
        //点击接单按钮时间
        LocalDateTime dateTime2 = LocalDateTime.parse(re.getCreatetime().substring(0, 19), formatter);
//		//开始维修时间
//		LocalDateTime dateTime3 = LocalDateTime.parse(re.getStartTime().substring(0,19), formatter);
//		//结束维修时间
//		LocalDateTime dateTime4 = LocalDateTime.parse(re.getEndTime().substring(0,19), formatter);
        //并修开始时间
        LocalDateTime dateTime5 = LocalDateTime.parse(re.getAuditdatetime().substring(0, 19), formatter);

        // 计算小时差
        long totalmaintenancetime = calculateHoursDifference(dateTime1, datenow);
        long orderreceivingtime = calculateHoursDifference(dateTime1, dateTime2);
        long waitingtime = calculateHoursDifference(dateTime5, dateTime1);
        long concurrentrepairtime = calculateHoursDifference(dateTime5, datenow);

        params.put("totalmaintenancetime", totalmaintenancetime);
        params.put("timeplus", orderreceivingtime);
        params.put("waitingtime", waitingtime);
        params.put("concurrentrepairtime", concurrentrepairtime);

        repairRecoedMapper.updateRepairStatussj1(params);

        // 查询维修记录
        RepairRecordInfo repairRecordInfo = repairRecoedMapper.selectRecordByRecordId(recordId.toString());

        //int newRequestId = (int) repairRecordTime.getRecordId();
        // 查询报修记录
        RequestInfo requestInfo = requestMapper.selectRequestVoById(repairRecordTime.getRecordId());
        // 插入消息通知记录
        EquipRepairMessageVo equipRepairMessageVo = new EquipRepairMessageVo();
        equipRepairMessageVo.setIsPush(BusinessConstants.IS_PUSH_TRUE);
        equipRepairMessageVo.setIsRead(BusinessConstants.IS_READ_FALSE);
        equipRepairMessageVo.setNewsType("维修验收");
        equipRepairMessageVo.setSendUser(requestInfo.getRequestUser());
        equipRepairMessageVo.setSiteKey(Long.valueOf(map.get("siteKey").toString()));

        Long relationId = Long.valueOf(repairRecordTime.getRecordId());
        equipRepairMessageVo.setRelationId(relationId);

        int newsiteKey = (int) siteKey;
        Long site = Long.valueOf(newsiteKey);
        equipRepairMessageVo.setSiteKey(site);
        equipRepairMessageVo.setEqKey(repairRecordInfo.getEqKey());
        equipRepairMessageVo.setNotingUser(repairRecordInfo.getRequestUser());
        // 根据设备id查询设备信息
        EmEquip emEquip = emEquipMapper.selectEmEquipById(repairRecordInfo.getEqKey());
        equipRepairMessageVo.setNewsDesc(
                "【维修验收】\n" + emEquip.getDesc() + "[" + emEquip.getName() + "]\n单号：" + repairRecordInfo.getRepairCode()
                        + "\n维修完成时间：" + finishTime.toString() + "\n维修人：" + repairUser.toString() + "\n请及时验收");
        equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);

        //在向群里发一条
        equipRepairMessageVo.setNotingUser("@all");
        equipRepairMapper.saveEquipRepairMessageInfo(equipRepairMessageVo);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("维修完成");
        return rspData;
    }

    /**
     * 保存报修文件信息
     */
    @PostMapping("/saveFile")
    public AjaxResult saveEquipSelfCheckInfo(@RequestBody RepairRecordInfo scv) {

        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        boolean result = repairRecordInfoService.saveRepairFile(scv, loginUser);
        if (!result) {
            return AjaxResult.error("保存自修信息！");
        }
        return AjaxResult.success();
    }


    @PostMapping("/selectHelpUser")
    public TableDataInfo selectHelpUser(@RequestBody RepairHelpUser repairHelpUser) {

        List<RepairHelpUser> list = repairRecordInfoService.selectHelpUser(repairHelpUser);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        rspData.setRows(list);
        return rspData;
    }


    @PostMapping("/selectEmFault")
    public TableDataInfo selectEmFault(@RequestBody EmFaultType emFaultType) {

        List<EmFaultTypeAndCode> faultTypeAndCodes = new ArrayList<EmFaultTypeAndCode>();
        // 获取当前登录用户
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if (loginUser.getUser().getDept().getParentId() != 0L && loginUser.getUser().getSite() != null) {
            emFaultType.setSiteKey(loginUser.getUser().getSite().toString());
        }
        // 根据工厂查询设备故障类型
        List<EmFaultType> typeList = emFaultTypeMapper.selectEmFaultTypeBySite(emFaultType);
        if (typeList.size() > 0) {
            EmFaultCode faultcode = new EmFaultCode();
            faultcode.setSiteKey(emFaultType.getSiteKey());
            List<EmFaultCode> codeList = emFaultCodeMapper.selectEmFaultCodeBySiteKey(faultcode);
            // 动态组合数据
            Iterator<EmFaultCode> iterator = codeList.iterator();
            for (EmFaultType faultType : typeList) {
                EmFaultTypeAndCode emFaultTypeNew = new EmFaultTypeAndCode();
                emFaultTypeNew.setText(faultType.getFaultDesc());
                // 初化子数据
                List<EmFaultTypeAndCode> faultTypeCodes = new ArrayList<EmFaultTypeAndCode>();
                while (iterator.hasNext()) {
                    EmFaultCode faultCode = iterator.next();
                    EmFaultTypeAndCode emFaultCodeNew = new EmFaultTypeAndCode();
                    if (faultCode.getFaultCode().equals(faultType.getFaultCode())) {
                        emFaultCodeNew.setText(faultCode.getItemDesc());
                        faultTypeCodes.add(emFaultCodeNew);
                        iterator.remove();
                        codeList.remove(faultCode);

                    }
                }
                if (faultTypeCodes.size() == 0) {
                    EmFaultTypeAndCode emFaultCodeNew = new EmFaultTypeAndCode();
                    emFaultCodeNew.setText("");
                    faultTypeCodes.add(emFaultCodeNew);
                    emFaultTypeNew.setChildren(faultTypeCodes);
                } else {
                    emFaultTypeNew.setChildren(faultTypeCodes);
                }
                faultTypeAndCodes.add(emFaultTypeNew);
                iterator = codeList.iterator();
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        rspData.setRows(faultTypeAndCodes);
        return rspData;
    }

    /**
     * 根据维修单ID刪除协助人信息
     *
     * @param repairHelpUser 维修协助人
     * @return
     */
    @PostMapping("/deleteHelpUserById")
    public TableDataInfo deleteHelpUserById(@RequestBody RepairHelpUser repairHelpUser) {
        repairRecordInfoService.deleteHelpUserById(repairHelpUser);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }


    @PostMapping("/insertHelpUser")
    public TableDataInfo insertHelpUser(@RequestBody Map<String, Object> map) {
        @SuppressWarnings("unchecked")
        List<RepairHelpUser> list = (List<RepairHelpUser>) map.get("list");
        repairRecordInfoService.insertHelpUser(list);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }

    /**
     * 根据维修单ID更新维修执行人
     *
     * @param map
     * @return
     */
    @PostMapping("/updateRepairUser")
    public TableDataInfo updateRepairUser(@RequestBody Map<String, Object> map) {
        repairRecordInfoService.updateRepairUser(map);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }

    /**
     * 根据报修单ID更新维修执行人
     *
     * @param map
     * @return
     */
    @PostMapping("/updateUserByRequstId")
    public TableDataInfo updateRepairUserByRequstId(@RequestBody Map<String, Object> map) {
        Long requestId = Long.valueOf((int) map.get("id"));
        map.put("requestId", requestId);
        if (requestId != null) {
            RepairRecordInfo repairRecordInfo = new RepairRecordInfo();
            repairRecordInfo.setRequestId(requestId);
            List<RepairRecordInfo> repairRecords = repairRecordInfoService.selectRepairByRequestId(repairRecordInfo);
            if (repairRecords.size() > 0) {
                LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
                map.put("checkUser", loginUser.getUser().getUserName());
                map.put("id", repairRecords.get(0).getId());
                repairRecordInfoService.updateRepairUser(map);
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }


    @PostMapping("/selectRepairByRequestId")
    public TableDataInfo selectRepairByRequestId(@RequestBody RepairRecordInfo repairRecordInfo) {
        List<RepairRecordInfo> repairRecords = repairRecordInfoService.selectRepairByRequestId(repairRecordInfo);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(repairRecords);
        rspData.setMsg("操作成功");
        return rspData;
    }


    @PostMapping("/updateRepairCheckStatus")
    public TableDataInfo updateRepairCheckStatus(@RequestBody Map<String, Object> map) {
        repairRecordInfoService.updateRepairCheckStatus(map);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }

    /**
     * 获取超过2小时维修未确认记录
     *
     * @return 列表明细
     */
    public TableDataInfo selectrepairrecordovertime() {
        List<RepairRecordInfo> repairRecordInfoList = repairRecordInfoService.selectRepairByRequestOverTime();
        return getDataTable(repairRecordInfoList);
    }

    public void updaterepairrecordovertime(Long id) {
        repairRecordInfoService.updateRepairByRequestOverTime(id);
    }

    @PostMapping("/addRepairTask")
    public void addRepairTask(@RequestBody Map<String, Object> map) {
        Object equipno = map.get("equipno");
        Object equipname = map.get("equipname");
        Object reason = map.get("reason");
        Object changeparts = map.get("changeparts");
        Object cycle = map.get("cycle");
        Object isused = map.get("isused");
        Object status = map.get("status");
        Object piclist = map.get("piclist");

        LocalDateTime now = LocalDateTime.now();
        String a = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toString();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("equipno", equipno.toString());
        params.put("equipname", equipname.toString());
        params.put("reason", reason.toString());
        params.put("changeparts", changeparts.toString());
        params.put("cycle", cycle.toString());
        params.put("isused", isused.toString());
        params.put("status", status.toString());
        params.put("piclist", piclist.toString());
        repairTaskMapper.insertInfo(params);

    }

    @PostMapping("/updateRepairTaskFile")
    public TableDataInfo updateRepairTaskFile(@RequestBody Map<String, Object> map) {
        repairTaskMapper.updateRepairTaskFile(map);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }

    @PostMapping("/updateTroubleInfo")
    public TableDataInfo updateTroubleInfo(@RequestBody Map<String, Object> map) {
        repairPlanMapper.updateTroubleInfo(map);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        return rspData;
    }


    @PostMapping("/selectRepairByNo")
    public TableDataInfo selectRepairByNo(@RequestBody RepairTask repairRecordInfo) {
        List<RepairTask> repairRecords = repairTaskMapper.selectRepairTaskList(repairRecordInfo);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(repairRecords);
        rspData.setMsg("操作成功");
        return rspData;
    }


    @PostMapping("/addTrouble")
    public void addTrouble(@RequestBody Map<String, Object> map) {
        Object hangameKey = map.get("hangameKey");
        Object siteKey = map.get("siteKey");
        Object equipno = map.get("equipno");
        Object equipname = map.get("equipname");
        Object troublecontent = map.get("troublecontent");
        Object managerid = map.get("managerid");
        Object managerchecked = map.get("managerchecked");
        Object createtime = map.get("createtime");
        Object resourcefrom = map.get("resourcefrom");
        Object piclist = map.get("piclist");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("hangameKey", hangameKey.toString());
        params.put("siteKey", siteKey.toString());
        params.put("equipno", equipno.toString());
        params.put("equipname", equipname.toString());
        params.put("troublecontent", troublecontent.toString());
        params.put("managerid", managerid.toString());
        params.put("managerchecked", managerchecked.toString());
        params.put("createtime", createtime.toString());
        params.put("resourcefrom", resourcefrom.toString());
        params.put("piclist", piclist.toString());

        repairPlanMapper.insertInfo(params);
    }

    @PostMapping("/selectTroubleList")
    public TableDataInfo selectList111(RepairPlan repairPlan) {
        List<RepairPlan> list = repairPlanMapper.selectTroubleList(repairPlan);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("操作成功");
        rspData.setRows(list);
        return rspData;
    }

    /**
     * 隐患排查推送测试
     */
    @Anonymous
    @GetMapping("push_message")
    public void test01(@RequestBody Map<String, Object> map) {
        String type = map.get("type").toString();
        if (type.equals("1")) {
            String pushMessage = "隐患编号:" + "【" + "BX2025102900000001" + "】\n设备名称：" + "测试设备" + "及联动系统已生成，请确认。";
            weChatMessageService.sendMessage(Long.valueOf(map.get("site").toString()), pushMessage, PushType.PUSH_TYPE_ONE.getValue(), null);
        } else if (type.equals("2")) {
            String pushMessage = "隐患编号：" + "【" + "BX2025102900000001" + "】\n设备名称：" + "测试设备" + "及联动系统重大隐患不成立，请重新判定。";
            weChatMessageService.sendMessage(Long.valueOf(map.get("site").toString()), pushMessage, PushType.PUSH_TYPE_TWO.getValue(), null);
        } else if (type.equals("3")) {
            String pushMessage = "隐患编号：" + "【" + "BX2025102900000001" + "】\n设备名称：" + "测试设备" + "及联动系统重大隐患已审核，请批示。";
            weChatMessageService.sendMessage(Long.valueOf(map.get("site").toString()), pushMessage, PushType.PUSH_TYPE_FOUR.getValue(), null);
        } else if (type.equals("4")) {
            String pushMessage = "<font color=\\\"warning\\\">工作任务管理系统-" + "隐患排查" + "提醒</font>\\n" + "隐患编号：" + "【" + "BX2025102900000001" + "】\n设备名称：" + "测试设备" + "及联动系统已生成，请确认。";
            weChatMessageService.sendMessage(Long.valueOf(map.get("site").toString()), pushMessage, PushType.PUSH_TYPE_FOUR.getValue(), "18341188987");
        }
    }
}
